package edu.towson.cosc.cosc455.cannon.compiler;

import java.io.*;
import java.util.ArrayList;

public class MyCompiler {
	
	static String token;
	static ArrayList<String> parseTree;
	static ArrayList<String> convertedDoc;
	static MyLexicalAnalyzer Lexer;
	static MySyntaxAnalyzer parser;
	static MySemanticAnalyzer generator;
	static String document;

	public static void main(String[] args) throws IOException {
		token= "";
		document = "";
		
		//check that there is 1 arg
		if (args.length != 1) {
			System.err.println("Error! There is not exactly 1 argument!");
			System.exit(0);
		}
		
		//setting up things to read the file
		FileReader fr = new FileReader(args[0]);
		BufferedReader br = new BufferedReader(fr);
		
		//reading the file line by line and putting it into "document"
		String sourceLine = null;
		while((sourceLine = br.readLine()) != null) {
			document += sourceLine;
		}
		
		//check extension
		if (!checkExtension(args[0])) {
			System.err.println("Error! The extension must be \".lol\"");
			System.exit(0);
		}
		
		//initialize parse tree array
		parseTree = new ArrayList<String>();
		
		//initialize stack for converting the file
		convertedDoc = new ArrayList<String>();
		
		Lexer = new MyLexicalAnalyzer();
		Lexer.getNextToken();
		
		parser = new MySyntaxAnalyzer();
		parser.lolcode();
		
		generator = new MySemanticAnalyzer();
		generator.generate();
		
		//write output file
		String outputFile = makeString(convertedDoc);
		File file = new File(args[0].substring(0, args[0].length()-4) + ".html");
		BufferedWriter output = new BufferedWriter(new FileWriter(file));
		output.write(outputFile);
		output.close();
		
		//clean up
		fr.close();
	}
	
	//gets the last 4 characters of the string and compares it to ".lol"
	static boolean checkExtension(String s) {
		return (s.substring(s.length()-4, s.length()).equals(".lol"));
	}
	
	//takes an ArrayList and puts it into a String with a nicer formatting than just putting each element on its own line
	//obviously could be a lot better
	static String makeString(ArrayList<String> t) {
		String doc = "";
		for (String s : t) {
			doc += s;
			if (s.equals("<html>") || s.equals("-->") || s.equals("<head>") || s.equals("</title>") || 
				s.equals("</head>") || s.equals("<br>") || s.equals("<audio controls>") || s.equals("<ul>") || 
				s.equals("</li>") || s.equals("</p>"))
				doc += "\n";
			else
				doc += " ";
		}
		return doc;
	}
}
